<?php
/**
 * 接口入口文件
 */
require_once __DIR__ . '/lib/utils.php';
require_once __DIR__ . '/model/DltDataModel.php';
require_once __DIR__ . '/model/SsqDataModel.php';
require_once __DIR__ . '/model/TaskModel.php';

switch ($_SERVER['PATH_INFO']) {
    case '/dlt/history':
        (new TaskModel())->run(false);
        json((new DltDataModel())->datasource(request('refresh', 'd') == '1'));
        break;
    case '/dlt/order-detail':
        json(getFileDetail(request('id', 'd'), 'dlt'));
        break;
    case '/ssq/history':
        (new TaskModel())->run(false);
        json((new SsqDataModel())->datasource());
        break;
    case '/task':
        (new TaskModel())->run();
        break;
    default:
        echo '404 Not Found';
        break;
}

function request($name, $type = 's')
{
    $type = strtolower($type);
    if ($type == 'd') {
        return filter_var($_REQUEST[$name], FILTER_SANITIZE_NUMBER_INT);
    }
    return strip_tags($_REQUEST[$name]);
}

function getFileList($module = 'dlt')
{
    $list = [];
    $fsi = new FilesystemIterator("./data/{$module}/");
    foreach ($fsi as $file) {
        if (str_starts_with($file->getFilename(), 'order-')) {
            $list[] = substr(basename($file->getFilename(), '.json'), 6);
        }
    }
    return $list;
}

function getFileDetail($drawNum, $module = 'dlt')
{
    $filePath = "./data/{$module}/order-{$drawNum}.json";
    if (!file_exists($filePath)) {
        return null;
    }
    return json_decode(file_get_contents($filePath), true);
}